package com.markerhub.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;

/**
 * 登录管理
 * @author 倪圳褒
 * @since 2024-01-25
 */
@Slf4j
@RestController
public class AuthController extends BaseController{
    @Autowired
    private Producer producer;
    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("调用图片验证码生成");

        String key= UUID.randomUUID().toString();
        String code= producer.createText();

        //测试
        key = "d743b546-c268-45de-81da-422e35c898f2";//存放位置
        code = "aaaaa";//验证码

        BufferedImage image=producer.createImage(code);
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img=str+ Base64Encoder.encode(outputStream.toByteArray());

        //captcha--uuid--验证码
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);

        return Result.succ(
                MapUtil.builder()
                        .put("token", key)
                        .put("captchaImg", base64Img)
                        .build()

        );
    }
    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal){
        SysUser sysUser=sysUserService.getByUsername(principal.getName());
        return Result.succ(MapUtil.builder()
                .put("id",sysUser.getId())
                .put("username",sysUser.getUsername())
                .put("avatar",sysUser.getAvatar())
                .put("created",sysUser.getCreated()).map()
        );
    }
}
